<template>
  <div class="discussion-container">
    <!-- 我的收藏按钮 -->
    <div class="favorites-button-container">
      <button @click="viewFavorites" class="favorites-button">
        我的收藏
      </button>
    </div>
    <h1 class="discussion-title">讨论区</h1>
    <p class="course-name">课程名称：{{ course.name }}</p>

    <div class="search-container">
      <input
        type="text"
        v-model="searchQuery"
        placeholder="搜索帖子和评论..."
        class="search-input"
      />
      <button @click="searchDiscussions" class="search-button">搜索</button>
    </div>

    <div class="discussions">
      <div
        v-for="discussion in discussions"
        :key="discussion.id"
        class="discussion-item"
      >
        <h4 class="discussion-header">
          {{ discussion.userName }} @ {{ discussion.date }}
        </h4>
        <p class="discussion-content">{{ discussion.content }}</p>
        <img v-if="discussion.image" :src="discussion.image" alt="讨论图片" class="discussion-image" />
        
        <div class="button-container">
          <button
            @click.stop="toggleLike(discussion)"
            :class="['like-button', { liked: discussion.liked }]"
          >
            {{ discussion.liked ? '取消点赞' : '点赞' }}
          </button>
          <span class="like-count">{{ discussion.likeCount }} 人点赞</span> <!-- 显示点赞数 -->
          
          <button
            @click.stop="toggleFavorite(discussion)"
            :class="['favorite-button', { favorited: discussion.favorited }]"
          >
            {{ discussion.favorited ? '取消收藏' : '收藏' }}
          </button>
          
          <!-- 新增的讨论区按钮 -->
          <button 
            @click.stop="goToDiscussionDetail(discussion)"
            class="discussion-detail-button"
          >
            进入讨论区
          </button>
        </div>
      </div>
    </div>

    <div class="comment-section">
      <h2>发布帖子</h2>
      <input
        type="text"
        v-model="newDiscussion.title"
        placeholder="输入帖子的标题..."
        class="discussion-title-input"
      />
      <textarea
        v-model="newDiscussion.content"
        placeholder="提出您的疑问或领悟..."
        class="discussion-textarea"
      ></textarea>
      <div class="input-container">
        <input
          type="file"
          @change="onImageChange"
          accept="image/*"
          class="file-input"
        />
        <button @click="submitDiscussion" class="submit-button">提交</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
  export default {
    data() {
      return {
        studentId: null,
        courseId: null,
        course: {}, // 存放课程信息
        discussions: [], // 存放讨论内容的数组
        newDiscussion: {
          title: "",
          content: "",
          image: null
        },
        searchQuery: "" // 新增搜索查询的状态
      };
    },
    created() {
      this.$store.commit('initializeState');  // 初始化 Vuex 状态
      this.studentId = this.$store.state.status.userId;
      this.courseId = this.$route.params.courseId; // 获取路由中的 courseId
      this.fetchCourseInfo(); // 获取课程信息
      this.fetchDiscussions(); // 获取讨论内容
      
      console.log("当前用户ID：", this.$store.state.status.userId);

    },
  
    methods: {
      
      // 提交新帖子
      async submitDiscussion() {
        if (!this.newDiscussion.title || !this.newDiscussion.content) {
          alert("标题和讨论内容不能为空!");
          return;
        }

        const newPost = {
          courseId: this.courseId,
          title: this.newDiscussion.title,
          content: this.newDiscussion.content,
          imageUrl: this.newDiscussion.image || "",
          studentId: this.studentId
        };

        try {
          console.log(newPost);
          const response = await axios.post('http://localhost:8085/posts/create', newPost);
          const post = response.data;
          console.log(post);
          this.discussions.push({
            id: post.postId,
            user: post.userId,
            title: post.title,
            content: post.content,
            image: post.image,
            date: new Date().toLocaleString(),
            liked: false, // 新增的“喜欢”状态
            favorited: false // 新增的“收藏”状态
          });
         
          // 重置新帖内容
          this.newDiscussion.title = "";
          this.newDiscussion.content = "";
          this.newDiscussion.image = null;
        } catch (error) {
          console.error("创建帖子失败:", error);
          alert("提交失败，请稍后再试！");
        }
      },

      // 跳转到帖子的讨论区
      goToDiscussionDetail(discussion) {
  if (discussion.postId) {
    // 将帖子信息保存到 localStorage
    localStorage.setItem('currentPost', JSON.stringify(discussion));
    
    // 跳转到讨论详情页面
    console.log("跳转到讨论详情，讨论 ID:", discussion.postId);
    this.$router.push({ name: 'DiscussionDetail', params: { discussionId: discussion.postId } });
  } else {
    console.error('无效的讨论 ID');
  }
},
      // 获取课程信息
      async fetchCourseInfo() {
        // API 调用获取课程信息
      },

      async fetchDiscussions() {
  try {
    const response = await axios.get(`http://localhost:8085/posts/postsWithLikes`, {
      params: {
        courseId: this.courseId,
        userId: this.studentId
      }
    });
    console.log("讨论列表数据:", response.data);

    // 确保返回的数据是 JSON 格式
    if (response.headers['content-type'].includes('application/json')) {
      this.discussions = response.data.map(post => {
        // 从 localStorage 获取该帖子的收藏状态
        const favorited = localStorage.getItem(`favorited-${post.post_id}`) === 'true';

        return {
          postId: post.post_id,
          title: post.title,
          content: post.content,
          image: post.image_url,
          likeCount: post.likeCount || 0,
          date: new Date(post.created_at).toLocaleString(),
          liked: post.isLiked === 1,
          favorited: favorited,  // 使用从 localStorage 获取的收藏状态
          userId: post.studentid
        };
      });
      console.log("获取的帖子详情:", this.discussions);
    } else {
      console.error('返回的不是 JSON 数据:', response);
      alert('数据格式错误，请稍后再试！');
    }
  } catch (error) {
    console.error('获取讨论失败:', error);
    alert('获取讨论失败，请稍后再试！');
  }
},

      // 图片上传处理
      onImageChange(event) {
        const file = event.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = e => {
            this.newDiscussion.image = e.target.result;
          };
          reader.readAsDataURL(file);
        }
      },

      async searchDiscussions() {
    try {
      const response = await axios.get(
        `http://localhost:8085/posts/search?keyword=${this.searchQuery}&courseId=${this.courseId}`
      );
      
      // 确保返回的数据正确，并进行映射
      this.discussions = response.data.map(post => ({
        postId: post.post_id,  // 映射 post_id 到 postId
        title: post.title,
        content: post.content,
        image: post.image_url,  // 修改为正确的字段名
        likeCount: post.likeCount || 0,  // 确保点赞数存在
        date: new Date(post.created_at).toLocaleString(),  // 格式化日期
        liked: post.isLiked === 1,  // 映射点赞状态
        favorited: false  // 收藏状态假设为 false，收藏按钮会根据此来判断是否已收藏
      }));

    } catch (error) {
      console.error("搜索帖子失败:", error);
      alert("搜索失败，请稍后再试！");
    }
  },
      async toggleLike(discussion) {
      try {
        console.log("当前讨论对象:", discussion);  // 查看discussion对象
        console.log("当前讨论的postId:", discussion.postId);  // 确认postId是否正确

        const data = new URLSearchParams({
          userId: this.studentId,
          postId: discussion.postId  // 使用映射后的字段 postId
        });

        if (discussion.liked) {
          // 取消点赞
          console.log("发送取消点赞请求的数据:", data.toString());
          await axios.post(`http://localhost:8085/posts/unlike`, data);
          discussion.liked = false;  // 更新状态
          discussion.likeCount -= 1;  // 减少点赞数
        } else {
          // 点赞
          console.log("发送点赞请求的数据:", data.toString());
          await axios.post(`http://localhost:8085/posts/like`, data);
          discussion.liked = true;  // 更新状态
          discussion.likeCount += 1;  // 增加点赞数
        }
      } catch (error) {
        console.error("点赞/取消点赞失败:", error);
        alert("操作失败，请稍后再试！");
      }
    },

    async toggleFavorite(discussion) {
  try {
    console.log("当前的 studentId:", this.studentId);

    const params = new URLSearchParams();
    params.append("userId", this.studentId);
    params.append("postId", discussion.postId);

    if (discussion.favorited) {
      // 如果已收藏，则取消收藏
      await axios.post('http://localhost:8085/posts/unfavorite', params);  // 发送 POST 请求
      discussion.favorited = false;
    } else {
      // 如果未收藏，则收藏
      await axios.post('http://localhost:8085/posts/favorite', params);  // 发送 POST 请求
      discussion.favorited = true;
    }

    // 保存收藏状态到 localStorage
    localStorage.setItem(`favorited-${discussion.postId}`, discussion.favorited);

  } catch (error) {
    console.error("收藏/取消收藏失败:", error);
    alert("操作失败，请稍后再试！");
  }
},

  async viewFavorites() {
    try {
      // 调用后端接口获取用户收藏的帖子
      const response = await axios.get('http://localhost:8085/posts/favorites', {
        params: {
          userId: this.studentId
        }
      });

      // 处理返回的数据，确保正确映射点赞和收藏的状态
      this.discussions = response.data.map(post => ({
        postId: post.post_id,
        title: post.title,
        content: post.content,
        image: post.image,
        likeCount: post.likeCount || 0,
        date: new Date(post.date).toLocaleString(),
        liked: post.isLiked === 1,  // 映射点赞状态
        favorited: true,  // 收藏状态应该始终为true，因为我们在收藏列表
      }));
    } catch (error) {
      console.error('获取收藏失败:', error);
      alert('获取收藏失败，请稍后再试！');
    }
  }
    }
    };
  </script>

<style scoped>
/* 新增按钮样式 */
/* 我的收藏按钮样式 */
.favorites-button-container {
  position: absolute;
  top: 20px;  /* 距离页面顶部 */
  left: 20px; /* 距离页面左边 */
  z-index: 100; /* 确保按钮在其他元素上方 */
}

.like-button,
.favorite-button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.favorites-button {
  background-color: #f8f9fa;
  border: 1px solid #007bff;
  color: #007bff;
  font-size: 16px;
  padding: 8px 16px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.favorites-button:hover {
  background-color: #007bff;
  color: white;
}

.like-button {
  background-color: #007bff;
  color: white;
}

.favorite-button {
  background-color: #28a745;
  color: white;
}

.like-button.liked {
  background-color: #ffc107; /* 黄色表示已喜欢 */
}

.favorite-button.favorited {
  background-color: #dc3545; /* 红色表示已收藏 */
}

.like-button:hover,
.favorite-button:hover {
  opacity: 0.8;
}

/* 容器和讨论项样式 */
.discussion-item {
  background-color: #fff;
  border: 1px solid #e1e1e1;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 15px;
  transition: box-shadow 0.3s;
}

.discussion-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
/* 新增样式：标题输入框 */
.discussion-title-input {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px;
}

.discussion-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.discussion-title {
  text-align: center;
  color: #333;
}

.course-name {
  text-align: center;
  color: #666;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.search-input {
  width: 70%;
  padding: 10px;
  border: 1px solid #007bff;
  border-radius: 5px 0 0 5px;
  outline: none;
  font-size: 14px;
}

.search-button {
  padding: 10px 15px;
  border: none;
  border-radius: 0 5px 5px 0;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #0056b3;
}

.discussions {
  margin-bottom: 20px;
}

.discussion-item {
  background-color: #fff;
  border: 1px solid #e1e1e1;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 15px;
  transition: box-shadow 0.3s;
}

.discussion-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.discussion-header {
  margin: 0 0 10px;
  font-size: 1.1em;
  color: #007bff;
}

.discussion-content {
  margin: 0 0 10px;
  line-height: 1.5;
}

.discussion-image {
  max-width: 100%;
  height: auto;
  margin-top: 10px;
  border-radius: 5px;
}

.comment-section {
  margin-top: 30px;
  padding: 15px;
  background-color: #fff;
  border: 1px solid #e1e1e1;
  border-radius: 5px;
}

.input-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.discussion-textarea {
  width: 100%;
  height: 100px;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  resize: none;
  font-size: 14px;
}

.file-input {
  margin-bottom: 10px;
  font-size: 14px;
  padding: 10px;
  border: 1px solid #0b7ffb;
  border-radius: 5px;
  background-color: rgba(244, 245, 249, 0.719)
  }
</style>